<template>
  <div class="register">
    <el-card class="container">
      <el-form
        ref="registerForm"
        :model="registerParams"
        :rules="rules"
        label-width="80px"
      >
        <!-- 昵称输入框 -->
        <el-form-item
          label="昵称"
          prop="name"
        >
          <el-input
            v-model="registerParams.name"
            type="input"
            style="width:250px"
          ></el-input>
        </el-form-item>
        <!-- 账号输入框 -->
        <el-form-item
          label="账号"
          prop="username"
        >
          <el-input
            v-model="registerParams.username"
            type="input"
            style="width:250px"
          ></el-input>
        </el-form-item>
        <!-- 密码输入框 -->
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="registerParams.password"
            type="password"
            style="width:250px"
          ></el-input>
        </el-form-item>
        <!-- 重复密码输入框 -->
        <el-form-item
          label="重复密码"
          prop="passwordRepeat"
        >
          <el-input
            v-model="registerParams.passwordRepeat"
            type="password"
            style="width:250px"
          ></el-input>
        </el-form-item>
        <!-- 年龄输入框 -->
        <el-form-item
          label="年龄"
          prop="age"
        >
          <el-input-number
            v-model="registerParams.age"
            style="width:250px"
          />
        </el-form-item>
        <!-- 性别输入框 -->
        <el-form-item
          label="性别"
          prop="sex"
        >
          <el-radio-group
            v-model="registerParams.sex"
          >
            <el-radio
              v-for="item in dictData"
              :key="item.value"
              :label="item.value"
              size="small"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 手机号输入框 -->
        <el-form-item
          label="手机号"
          prop="phoneNumber"
        >
          <el-input
            v-model="registerParams.phoneNumber"
            type="input"
            style="width:250px"
          ></el-input>
        </el-form-item>
        <!-- 邮箱号输入框 -->
        <el-form-item
          label="邮箱号"
          prop="email"
        >
          <el-input
            v-model="registerParams.email"
            type="input"
            style="width:250px"
          ></el-input>
        </el-form-item>
        <!-- 邮箱验证码输入框 -->
        <el-form-item
          label="验证码"
          prop="emailCode"
        >
          <el-input
            v-model="registerParams.emailCode"
            type="input"
            style="width:130px"
          ></el-input>
          <el-link
            style="width:120px;color: #337ecc;"
            @click="reduceSendEmail()"
          >
            {{ interval == 0 ? '发送邮箱验证' : `已发送(${interval})` }}
          </el-link>
        </el-form-item>
        <!-- 操作按钮 -->
        <el-form-item>
          <div class="btns">
            <el-button
              size="small"
              type="primary"
              @click="submitForm()"
            >
              注册
            </el-button>
            <el-button 
              size="small"
              @click="resetForm()"
            >
              清空
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <el-link
        class="register_link"
        @click="toRegister()"
      >
        去登录
      </el-link>
    </el-card>
  </div>
</template>

<script lang='ts' setup name="register">
import api from './service/api'
import { ref, reactive, onBeforeUnmount, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import Md5 from 'md5'
import commonApi from '@/api/common'

const dictData = ref()
const router = useRouter()
// 收集的注册信息
const registerParams = reactive({
    name: '',
    username: '',
    password: '',
    passwordRepeat: '',
    age: 0,
    sex: 0,
    phoneNumber: '',
    email: '',
    emailCode: '', 
})

const registerForm = ref<FormInstance>()

// 表单校验
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 3, max: 20, message: '昵称长度应在3~20之间', trigger: 'blur' },
    ],
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度应在3~20之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 20, message: '密码长度应在5~20之间', trigger: 'blur' },
    ],
    passwordRepeat: [
        { required: true, message: '请重复输入密码', trigger: 'blur' },
        { validator: () => registerParams.password == registerParams.passwordRepeat, 
            message: '密码不一致', 
            trigger: 'blur', 
        },
    ],
    phoneNumber: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱号', trigger: 'blur' },
    ],
    emailCode: [
        { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    ],
})

// 提交注册信息
const submitForm = () => {
    let commitParams = {
        name: registerParams.name,
        username: registerParams.username,
        password: registerParams.password,
        age: registerParams.age,
        sex: registerParams.sex,
        phoneNumber: registerParams.phoneNumber,
        email: registerParams.email,
        emailCode: registerParams.emailCode,
    }
    if (registerForm.value) {
        registerForm.value.validate((valid) => {
            if (valid) {
                commitParams.password = Md5(registerParams.password)
                api.userRegister(commitParams).then(res => {
                    const { code, data, msg } = res
                    if (code === 0) {
                        toRegister()
                        ElMessage({
                            message: msg,
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: msg,
                            type: 'error',
                        })
                    }
                })
            } else {
                ElMessage({
                    message: '信息填写不完整',
                    type: 'warning',
                })
                return false
            }
        })
    }
}

// 清空表单数据
const resetForm = () => {
    if (registerForm.value) {
        registerForm.value.resetFields()
    }
}

const interval = ref(0)
const timer = ref(0)
// 发送邮箱验证码
const reduceSendEmail = () => {
    if (interval.value == 0) {
        sendEmail()
        interval.value = 60
        emailTimeOut()
    } else {
        ElMessage({
            message: '每60s只能发送一次邮件',
            type: 'warning',
        })
    }
}
const emailTimeOut = () => {
    timer.value = window.setInterval(() => { 
        if (interval.value > 0) {
            interval.value--
        } else {
            clearInterval(timer.value)
        }
    }, 1000)
}
const sendEmail = () => {
    let data = { email: registerParams.email }
    api.sendEmail(data).then(res => {
        const { code, data, msg } = res
        if (code == 0) {
            ElMessage({
                message: msg,
                type: 'success',
            })
        } else {
            ElMessage({
                message: msg,
                type: 'error',
            })
        }
    })
}

const toRegister = () => {
    router.push('/login')
}

const getDictList = () => {
    commonApi.getDict('sex').then(res => {
        const { code, msg, data } = res
        if (code == 0) {
            dictData.value = data
        } else {
            ElMessage({
                message: msg,
                type: 'warning',
            })
        }
    })
}

onMounted(() => {
    getDictList()
})
onBeforeUnmount(() => {
    clearInterval(timer.value)
})
</script>
<style lang='scss' scoped>
.register{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background: url('../../assets/login/bg.jpeg') no-repeat;
  background-size:  100% 100%;
  .container{
    width: 450px;
    height: 580px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    .btns{
      width: 180px;
      margin-top: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .register_link{
      position: absolute;
      right: 30px;
      bottom: 20px;
      color: #337ecc;
    }
  }
}
</style>